<!-- components/reconciliation/AnalysisReportDialog.vue -->
<template>
  <el-dialog
    v-model="visible"
    title="智能分析报告"
    width="80%"
    class="analysis-report-dialog"
    :before-close="handleClose"
  >
    <div v-loading="loading" class="report-content">
      <!-- 报告头部信息 -->
      <div class="report-header">
        <div class="header-info">
          <h2>对账智能分析报告</h2>
          <p>生成时间: {{ reportData?.reportDate ? formatDateTime(reportData.reportDate) : '' }}</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" :icon="Download" @click="exportReport">
            导出报告
          </el-button>
        </div>
      </div>

      <!-- 如果报告正在生成中 -->
      <div v-if="generating" class="generating-state">
        <el-skeleton animated>
          <template #template>
            <el-skeleton-item variant="h3" style="width: 50%" />
            <div style="margin-top: 20px">
              <el-skeleton-item variant="p" style="width: 100%" />
              <el-skeleton-item variant="p" style="width: 80%; margin-top: 10px" />
            </div>
          </template>
        </el-skeleton>
      </div>

      <!-- 报告内容 -->
      <div v-else-if="reportData" class="report-body">
        <!-- 统计概览 -->
        <el-card class="report-section" shadow="never">
          <template #header>
            <div class="card-header">
              <span>统计概览</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ reportData.statistics?.totalProcessed || 0 }}</div>
                <div class="stat-label">总处理数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value success">{{ reportData.statistics?.matchedCount || 0 }}</div>
                <div class="stat-label">已匹配数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value warning">{{ reportData.statistics?.highConfidenceCount || 0 }}</div>
                <div class="stat-label">高置信度匹配</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value info">{{ reportData.statistics?.avgConfidence || 0 }}%</div>
                <div class="stat-label">平均置信度</div>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 趋势分析 -->
        <el-card class="report-section" shadow="never">
          <template #header>
            <div class="card-header">
              <span>趋势分析</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="trendChartRef" class="chart"></div>
          </div>
        </el-card>

        <!-- 智能建议 -->
        <el-card class="report-section" shadow="never">
          <template #header>
            <div class="card-header">
              <span>智能建议</span>
            </div>
          </template>
          <div class="suggestions-container">
            <el-empty v-if="!reportData.suggestions || reportData.suggestions.length === 0" description="暂无建议" />
            <el-alert
              v-for="suggestion in reportData.suggestions"
              :key="suggestion.id"
              :title="suggestion.title"
              :type="getAlertType(suggestion.type)"
              :description="suggestion.description"
              show-icon
              :closable="false"
            />
          </div>
        </el-card>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error-state">
        <el-result
          icon="error"
          title="报告生成失败"
          :sub-title="error"
        >
          <template #extra>
            <el-button type="primary" @click="retryGenerate">重新生成</el-button>
          </template>
        </el-result>
      </div>

      <!-- 初始状态 -->
      <div v-else class="empty-state">
        <el-result
          icon="info"
          title="暂无报告数据"
          sub-title="点击生成按钮开始生成智能分析报告"
        />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="generateReport">重新生成</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 定义属性
const props = defineProps<{
  modelValue: boolean
  data?: any
}>()

// 定义事件
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'generate', params?: any): void
}>()

// 响应式数据
const visible = ref(false)
const loading = ref(false)
const generating = ref(false)
const error = ref('')
const reportData = ref<any>(null)
const trendChartRef = ref<HTMLDivElement | null>(null)
let trendChart: echarts.ECharts | null = null

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 获取警告类型
const getAlertType = (type: string) => {
  switch (type) {
    case 'warning': return 'warning'
    case 'error': return 'error'
    case 'info': return 'info'
    default: return 'success'
  }
}

// 处理关闭
const handleClose = () => {
  visible.value = false
  emit('update:modelValue', false)
}

// 生成报告
const generateReport = () => {
  emit('generate')
}

// 重新生成
const retryGenerate = () => {
  error.value = ''
  generateReport()
}

// 导出报告
const exportReport = () => {
  ElMessage.info('导出功能待实现')
}

// 初始化趋势图表
const initTrendChart = () => {
  if (trendChartRef.value) {
    // 销毁之前的图表实例
    if (trendChart) {
      trendChart.dispose()
    }
    
    // 初始化新的图表实例
    trendChart = echarts.init(trendChartRef.value)
    
    // 设置图表选项
    const option = {
      title: {
        text: '回款周期趋势'
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      },
      yAxis: {
        type: 'value',
        name: '天数'
      },
      series: [
        {
          data: [120, 200, 150, 80, 70, 110, 130],
          type: 'line',
          smooth: true
        }
      ]
    }
    
    // 设置图表选项
    trendChart.setOption(option)
  }
}

// 监听数据变化
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
})

watch(() => props.data, (newData) => {
  if (newData) {
    reportData.value = newData
    generating.value = false
    loading.value = false
    
    // 在下一个DOM更新周期初始化图表
    nextTick(() => {
      initTrendChart()
    })
  }
})

// 监听可见性变化
watch(visible, (newVal) => {
  if (!newVal) {
    // 关闭时清理资源
    if (trendChart) {
      trendChart.dispose()
      trendChart = null
    }
  }
})

// 组件挂载时初始化
onMounted(() => {
  visible.value = props.modelValue
})
</script>

<style scoped lang="scss">
.analysis-report-dialog {
  .report-content {
    min-height: 500px;
    
    .report-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #eee;
      
      .header-info {
        h2 {
          margin: 0 0 10px 0;
          font-size: 20px;
          color: #303133;
        }
        
        p {
          margin: 0;
          color: #909399;
          font-size: 14px;
        }
      }
    }
    
    .report-body {
      .report-section {
        margin-bottom: 20px;
        
        .card-header {
          font-weight: 600;
          font-size: 16px;
          color: #303133;
        }
        
        .stat-item {
          text-align: center;
          padding: 20px 0;
          
          .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 5px;
            
            &.success {
              color: #67c23a;
            }
            
            &.warning {
              color: #e6a23c;
            }
            
            &.info {
              color: #409eff;
            }
          }
          
          .stat-label {
            font-size: 14px;
            color: #909399;
          }
        }
        
        .chart-container {
          height: 400px;
          
          .chart {
            width: 100%;
            height: 100%;
          }
        }
        
        .suggestions-container {
          .el-alert {
            margin-bottom: 15px;
          }
        }
      }
    }
    
    .generating-state {
      padding: 30px 0;
    }
    
    .error-state, .empty-state {
      padding: 50px 0;
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}
</style>